<!--二手房 修改 -->
<template>
  <div
    class="app-container"
    v-loading.fullscreen="loading"
    :element-loading-text="loadText"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="nav-box">
      <el-collapse-transition>
        <div v-show="navShow">
          <div
            v-for="(item, i) in navList"
            :key="item.title"
            :class="{ 'nav-item': true, select: navCurrentIndex == i }"
            @click="handleAnchor(i, item.nav)"
          >
            {{ item.title }}
          </div>
        </div>
      </el-collapse-transition>
      <div @click="navShow = !navShow" :class="['nav-item', navShow ? '' : 'select']">
        <span :class="[navShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down', 'fs-xxl']"></span>
      </div>
    </div>
    <div>
      <com-title-item title="房源信息修改">
        <el-form :model="houDelVO" label-width="110px" size="mini" style="margin-top: 20px">
          <el-form-item
            v-for="(configItem, index) in configHouse"
            :label="configItem.title"
            :key="index"
            :prop="configItem.key"
            :rules="configItem.rules || []"
          >
            <!-- 单选 -->
            <template v-if="configItem.isRadio && configItem.options">
              <el-radio-group v-model="houDelVO[configItem.key]">
                <el-radio v-for="(item, i) in configItem.options" :label="item" :key="i">{{
                  configItem.format ? configItem.format(item) : item
                }}</el-radio>
              </el-radio-group>
            </template>

            <!-- 多选 -->
            <template v-else-if="configItem.isCheckbox && configItem.options">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <el-checkbox-group v-model="houDelVO[configItem.key]" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="item in configItem.options" :label="item" :key="item">{{
                  configItem.format ? configItem.format(item) : item
                }}</el-checkbox>
              </el-checkbox-group>
            </template>

            <!-- 单输入框 -->
            <template v-else-if="configItem.isInput">
              <el-input
                :disabled="configItem.disabled"
                :suffix-icon="configItem.disabled ? 'el-icon-lock' : ''"
                v-model="houDelVO[configItem.key]"
                :style="{ width: configItem.width }"
              >
                <i v-if="configItem.unit" slot="suffix" style="font-style: normal">{{ configItem.unit }}</i>
              </el-input>
            </template>

            <!-- 多输入框 -->
            <template v-else-if="configItem.isMultiple">
              <el-row :gutter="10">
                <template v-for="(item, i) in configItem.contents">
                  <el-col :span="configItem.contents.length == 5 ? 2 : 3" :key="i">
                    <el-form-item :prop="item.key" :rules="item.rules || []">
                      <el-input v-model="houDelVO[item.key]" :placeholder="item.placeholder" :readonly="item.readonly">
                        <i slot="suffix" style="font-style: normal">{{ item.unit }}</i>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </template>
              </el-row>
            </template>

            <!-- 额外按钮 -->
            <template v-if="configItem.button">
              <el-button style="margin-left: 10px" type="primary" @click="handleSetDefaultValue(configItem)">{{
                configItem.button.buttonText
              }}</el-button>
            </template>
            <!-- 小提示 -->
            <template v-if="configItem.tips">
              <span class="text-gray" style="margin-left: 15px">{{ configItem.tips }}</span>
            </template>
          </el-form-item>
        </el-form>
      </com-title-item>

      <com-title-item title="房源介绍">
        <com-recommend
          :houDelRecommendVO="houDelRecommendVO"
          :houDelRecommendErrorMsg="houDelRecommendErrorMsg"
          :houDelVO="houDelVO"
        ></com-recommend>
      </com-title-item>

      <com-title-item title="图片信息">
        <com-image-list
          :imageVO="imageVO"
          :houDelId="houDelId"
          :isVrHouse="hmDelSummaryInfo.houSubType == 1"
          :houDelVO="houDelVO"
          :houImageVO="houImageVO"
        ></com-image-list>
      </com-title-item>

      <!-- 视频信息 -->
      <com-title-item title="视频信息">
        <com-upload-video
          :hmDelSummaryInfo="hmDelSummaryInfo"
          @onvideoupdate="handleVideoDuringUpdate"
          :room="houDelVO.room"
          :houDelId="houDelId"
        >
          <template #default="{...row}">
            <com-table-video v-bind="row"></com-table-video>
          </template>
        </com-upload-video>
        <div>
          <div class="vr d-flex ai-center fs-l" v-if="showDownLoadVr">
            <div class="title">下载VR房源</div>
            <div class="select">
              <el-radio v-model="radio" label="1">是</el-radio>
              <el-radio v-model="radio" label="2">否</el-radio>
            </div>
          </div>
          <div v-if="showDownLoadVr" class="fs-md text-gray-light" style="margin-top: 10px">
            备注：当房源为VR房源时才可以进行VR下载，VR预计5分钟后下载完成
          </div>
          <div class="comfirm d-flex ai-center jc-center">
            <el-button type="info" @click="$router.back()">取消</el-button>
            <el-button type="primary" :disabled="!saveAble" @click="handleConfirm">保存</el-button>
          </div>
        </div>
      </com-title-item>

      <!-- 保存成功的弹层 -->
      <el-dialog :visible.sync="nextPopVisible" top="30vh">
        <span slot="title" class="d-flex ai-center">
          <span class="el-icon-success text-green fs-xxxl"></span>
          <span style="margin-left: 8px">保存成功</span>
        </span>
        <span>{{
          houseInfoCompleted
            ? '房源信息已完备，请确认图片水印已去除、房源信息无误后再进行推送～'
            : '房源信息未完善，完善之后才能进行推房～'
        }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button plain @click="nextPopVisible = false">{{
            houseInfoCompleted ? '返回确认' : '立即完善'
          }}</el-button>
          <el-button type="primary" @click="$router.replace({ name: 'PublishHouseList' })">返回列表</el-button>
        </span>
      </el-dialog>

      <!-- 设置佣金等默认值 -->
      <com-set-default-pop
        :configItem="setDefaultPopConfig"
        :popVisible.sync="setDefaultPopVisible"
        @onsetdefaultvalue="handleConfirmDefaultValue"
      ></com-set-default-pop>
    </div>
  </div>
</template>

<script>
import ComTitleItem from '@/views/house/com/com-title-item';
import ComMatchItem from '@/views/house/com/com-match-item';
import ComSetDefaultPop from '@/views/house/dialog/com-set-default-pop';
import ComUploadVideo from '@/views/house/com/com-upload-video';
import ComTableVideo from '@/views/house/com/com-table-video';
import ComImageList from '@/views/house/com/com-image-list';
import ComRecommend from '@/views/house/com/com-recommend';
import ComPortTag from '@/views/house/com/com-port-tag';
import ComReHsh from '@/views/house/com/com-re-hsh';
import ComCellItem from '@/views/house/com/com-cell-item';
import ComNoPortaccount from '@/views/house/com/com-no-portaccount';

import {
  getHouseInfo,
  updateImage,
  updateRecommendInfo,
  getMemberPower,
  submitVrTask,
  updateDelInfoWeb,
  examineDelPushAble
} from '@/api/user';
import { menuHandler } from '@/handler/menuHandler';
import { HOUSE_PUSH, VIP_MESSAGE, VR_COMPOUND_ADD } from '@/config/menuId';
import { mapGetters } from 'vuex';
import {
  configHouse,
  hallRoomNumber,
  houseRecommend,
  houseImages,
  portHouNumConfig,
  videoTimeList,
  forceHouseInfoHanlder
} from '@/config/house/houseDetailConfig';

import { SALES } from '@/config/house/houDelVOKeys';

const checkboxOptions = configHouse.find((v) => v.isCheckbox).options;
const navList = [
  { title: '房源信息修改', nav: 0 },
  { title: '房源介绍', nav: 1110 },
  { title: '图片信息', nav: 2300 },
  { title: '视频信息', nav: 2817 }
];
export default {
  components: {
    ComTitleItem,
    ComMatchItem,
    ComSetDefaultPop,
    ComUploadVideo,
    ComTableVideo,
    ComImageList,
    ComRecommend,
    ComPortTag,
    ComReHsh,
    ComCellItem,
    ComNoPortaccount
  },
  props: {
    houDelId: {
      type: String,
      default: ''
    }
  },
  provide() {
    return {
      submitImage: this.submitImage,
      houDelVO: this.houDelVO
    };
  },
  data() {
    return {
      platformVerifyVisible: true,
      videoDuringTime: 0, //视频播放时长
      loadText: '拼命加载中...',
      setDefaultPopConfig: {}, //设置默认值的配置信息（佣金比例/）
      setDefaultPopVisible: false, //设置默认值的小弹层
      houseInfoCompleted: true, //房源信息是否完善
      navShow: true,
      navCurrentIndex: 0,
      navList: navList,
      radio: '1',
      isFromMovePage: false,
      loading: false,
      nextPopVisible: false, //保存完成后的下一步选择弹层
      checkAll: false,
      isIndeterminate: false,

      portTags: [],
      // 基本信息
      houDelVO: {
        ...SALES,

        totalPricesPassed: false, //是否总价通过校验
        totalPricesIgnore: false //是否总价忽略校验
      },
      houPortInfo: [], //匹配端口小区信息列表
      houDelRecommendVO: {
        title: '',
        sellingPoint: '', //核心卖点
        ownerPsychology: '', //业主心态
        serviceIntroduction: '', //服务介绍
        surroundMating: '', // 小区配套
        service: '' //税费信息
      },
      // 错误提示
      houDelRecommendErrorMsg: {
        title: '',
        sellingPoint: '', //核心卖点
        ownerPsychology: '', //业主心态
        serviceIntroduction: '', //服务介绍
        surroundMating: '', // 小区配套
        service: '' //税费信息
      },
      imageVO: {
        houseTypeList: [], //房型图
        indoorList: [], //室内图
        circumList: [] //小区图
      },
      houImageVO: [], //图片原始数据
      configHouse: Object.freeze(configHouse),
      hallRoomNumber: hallRoomNumber,
      houseRecommend: Object.freeze(houseRecommend),
      houseImages: Object.freeze(houseImages),
      portHouNumConfig: Object.freeze(portHouNumConfig),
      hmDelSummaryInfo: {} //关于vr视频的数据
    };
  },

  created() {
    // window.onscroll = () => {
    //   console.log(document.documentElement.scrollTop)
    // }
  },
  watch: {
    houDelRecommendVO: {
      handler(newVal) {
        const { houDelRecommendErrorMsg } = this;
        // 房源介绍
        houseRecommend.forEach((item) => {
          let value = newVal[item.key];
          if (!item.required) return;

          let errorMsg = item.rule(value);
          houDelRecommendErrorMsg[item.key] = errorMsg;
        });
      },
      deep: true
    }
  },
  async mounted() {
    let item = configHouse.find((v) => v.title == '佣金比例');
    this.setDefaultPopConfig = item;

    this.initHouseInfo(this.houDelId);
  },

  computed: {
    ...mapGetters(['sessionUser']),
    ...mapGetters(['sidebar']),
    saveAble({ houDelVO }) {
      return forceHouseInfoHanlder(houDelVO);
    },
    averagePrice() {
      let totalPrices = this.houDelVO.totalPrices;
      let buildSize = this.houDelVO.buildSize;
      if (!totalPrices || !buildSize) return '';
      return (totalPrices / buildSize).toFixed(2) + '万';
    },

    showDownLoadVr() {
      let info = this.hmDelSummaryInfo;
      return info.houSubType == 1 && info.houSubTypeState != 10 && info.houSubTypeState != 1;
    }
  },

  methods: {
    handleVideoDuringUpdate(value) {
      this.videoDuringTime = value;
    },
    // 初始化房源基本信息
    async initHouseInfo(houDelId) {
      this.loading = true;
      const { content, isSuccess, errorCode } = await getHouseInfo({ houDelId });
      if (!isSuccess && errorCode && errorCode === '21007') {
        this.$alert('该房源被删除，无法查看~', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          callback: (action) => {
            this.$router.back();
          }
        });
        return;
      }

      this.hmDelSummaryInfo = content.hmDelSummaryInfo || {};
      content.houDelVO.portHouNum = content.houDelVO.portHouNum || '1' + String(Math.random()).slice(-9);

      this.renderHouDel(content.houDelVO);
      this.houImageVO = Object.freeze(content.houImageVO);
      this.renderRecommend(content.houDelRecommendVO, content.houDelVO.title);

      this.loading = false;
    },

    // 保存
    async handleConfirm() {
      this.loading = true;

      try {
        await this.requeryUpdateRecommendInfo();
        await this.submitHouDel();
        await this.submitImage();

        await examineDelPushAble({ delId: this.houDelId });
      } catch (error) {
        this.loading = false;
        return;
      }

      this.loading = false;

      if (!this.showDownLoadVr || this.radio == '2') {
        this.nextPopVisible = true;
      } else {
        await this.downLoadVR();
        this.nextPopVisible = true;
      }
    },

    // 锚点
    handleAnchor(i, nav) {
      if (typeof nav == 'undefined') {
        nav = navList[i].nav;
      }
      if (nav || nav === 0) {
        this.navCurrentIndex = i;
        document.documentElement.scrollTop = document.body.scrollTop = nav;
      } else {
        this.navCurrentIndex = 0;
        if (this.navList.length == 1) {
          this.navList = navList;
        } else {
          this.navList = [navList[navList.length - 1]];
        }
      }
    },
    downLoadVR() {
      return menuHandler
        .call(this, VR_COMPOUND_ADD)
        .then(() => {
          submitVrTask({
            delId: this.houDelId
          }).then(() => {
            this.hmDelSummaryInfo.houSubTypeState = 1;
          });

          getMemberPower({
            menuId: VR_COMPOUND_ADD,
            agentId: this.sessionUser.id
          });

          return this.$messageBox
            .confirm('vr房源下载中，需要3-5分钟', {
              confirmButtonText: '我知道了',
              showCancelButton: false
            })
            .finally(() => {
              return Promise.resolve();
            });
        })
        .catch((error) => {
          if (error && error.then) {
            return error.then(() => Promise.reject());
          } else {
            return Promise.resolve();
          }
        });
    },

    isVipMember() {
      return new Promise((resolve, reject) => {
        menuHandler
          .call(this, HOUSE_PUSH)
          .then(() => {
            resolve();
          })
          .catch((error) => {
            reject();
          });
      });
    },

    // 校验基本信息
    checkValues() {
      for (let i = 0; i < configHouse.length; i++) {
        const item = configHouse[i];
        if (!item.required) continue;

        if (item.key) {
          if (item.checkValue && !item.checkValue(this.houDelVO[item.key])) {
            this.$message.error(`${item.title}不合格或含有空格`);
            return true;
          }

          if (item.isRadio) {
            if (!this.houDelVO[item.key] && this.houDelVO[item.key] !== 0) {
              this.$message.error(`${item.title}未填`);
              return true;
            }
          }
        }

        if (item.isMultiple && item.contents && item.checkValue) {
          for (let j = 0; j < item.contents.length; j++) {
            const element = item.contents[j];
            if (!item.checkValue(this.houDelVO[element.key])) {
              this.$message.error(`${item.title}不合格或含有空格`);
              return true;
            }
          }
        }
      }

      for (let i = 0; i < houseRecommend.length; i++) {
        const item = houseRecommend[i];
        if (!item.required) continue;

        let value = this.houDelRecommendVO[item.key] || '';
        let errorMsg = item.rule(value);
        if (errorMsg) {
          this.$message.error(errorMsg);
          return true;
        }
      }

      return false;
    },

    renderHouDel(vo) {
      vo = this.houDelVOFormat(vo);
      for (let key in this.houDelVO) {
        if (key in vo) {
          this.houDelVO[key] = vo[key];
        }
      }
      this.houDelVO.totalPrices = this.getTotalPrices(vo);
    },

    /** 获取视频最小时长限制 */
    getVideoMinTime() {
      let room = this.houDelVO.room;
      if (room && room != '0' && this.videoDuringTime) {
        let minTime = videoTimeList[room] || Math.max.apply(null, Object.values(videoTimeList));
        if (this.videoDuringTime < minTime) {
          return `${room}室户上传视频不得小于${minTime}秒`;
        }
      }
      return '';
    },
    submitHouDel() {
      let errorMsg = this.getVideoMinTime();
      if (errorMsg) {
        return this.$messageBox
          .confirm(errorMsg, {
            confirmButtonText: '我知道了',
            cancelButtonText: '去修改'
          })
          .finally(() => {
            return Promise.reject();
          });
      }

      let obj = {
        id: this.houDelId,
        ...this.houDelVO,
        title: this.houDelRecommendVO.title,
        totalPrices: this.setTotalPrices(this.houDelVO),
        matchingFacilities: this.houDelVO.matchingFacilitiesList.join(',')
        // delPercentage: String(this.percentage / 100),
      };

      return updateDelInfoWeb({
        houDelStr: JSON.stringify(obj)
      }).then(({ isSuccess, errorMessage = '' }) => {
        if (!isSuccess) {
          if (this.houDelVO.hasOwnProperty(errorMessage)) {
            this.houDelVO[errorMessage] = '';
          }

          return this.$messageBox
            .confirm(`保存房源基本信息失败，${errorMessage}`, {
              confirmButtonText: '我知道了',
              showCancelButton: false
            })
            .finally(() => {
              return Promise.reject();
            });
        }
      });
    },

    renderRecommend(list, title) {
      this.houDelRecommendVO.title = title;
      for (let key in this.houDelRecommendVO) {
        if (list && list[key]) {
          let item = houseRecommend.find((v) => v.key == key);
          this.houDelRecommendVO[key] = list[key].context || (item && item.defaultValue);
        }
      }
    },

    requeryUpdateRecommendInfo() {
      return updateRecommendInfo({
        houDelRecStr: JSON.stringify({
          deleted: false,
          houDelId: this.houDelId,
          ...this.getRecommendVo(this.houDelRecommendVO, houseRecommend)
        })
      }).then(({ isSuccess, errorMessage }) => {
        if (!isSuccess) {
          this.$message.error(errorMessage);
          return Promise.reject(0);
        }
      });
    },

    submitImage() {
      let houImgList = [...this.imageVO.indoorList, ...this.imageVO.houseTypeList, ...this.imageVO.circumList];
      houImgList.forEach((item, index) => {
        item.cover = index;
      });

      return updateImage({ houImgList })
        .catch((error) => {
          this.$message.error('图片保存超时！');
          return Promise.reject();
        })
        .then(({ isSuccess, errorMessage = '' }) => {
          if (!isSuccess) {
            return this.$messageBox
              .confirm(`保存图片失败，${errorMessage}`, {
                confirmButtonText: '我知道了',
                showCancelButton: false
              })
              .finally(() => {
                return Promise.reject();
              });
          }
        });
    },

    handleCheckAllChange(val) {
      this.houDelVO.matchingFacilitiesList = val ? checkboxOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === checkboxOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < checkboxOptions.length;
    },

    handleSetDefaultValue(configItem) {
      this.setDefaultPopVisible = true;
      this.setDefaultPopConfig = configItem;
    },
    handleConfirmDefaultValue(v) {
      this.houDelVO.commissionRate = v;
    }
  }
};
</script>

<style scoped>
ul {
  padding: 0;
  margin: 0;
}
.modify-box {
  position: relative;
  overflow: hidden;
}
.header-process {
  position: fixed;
  left: 0;
  right: 0;
  top: 84px;
  background: #fff;
  z-index: 10;
  padding: 0 50px 0 30px;
  line-height: 30px;
  transition: all 0.3s;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.nav-box {
  position: fixed;
  width: 120px;
  text-align: center;
  line-height: 50px;
  background: rgba(255, 255, 255, 0.7);
  box-shadow: rgba(0, 0, 0, 0.3) 0px 0px 15px;
  z-index: 10;
  cursor: pointer;
  right: 0;
  top: 30%;
}
.nav-box .nav-item {
  display: block;
  border-bottom: 1px solid #eee;
}
.nav-box .nav-item.select {
  background: rgb(68, 161, 255);
  color: #fff;
}

.app-container {
  background: #f6f6f6;
  /* padding-top: 50px; */
}

.app-container .comfirm {
  margin-top: 30px;
}

.app-container >>> .el-radio-group .el-radio {
  margin-top: 2px;
  margin-bottom: 2px;
}

.vr {
  margin-top: 50px;
}
.vr .title {
  margin-right: 10px;
}

.vr .select {
  margin-right: 30px;
}

.reject-input >>> .el-textarea__inner {
  border-color: red;
}
.reject-input >>> .el-input__inner {
  border-color: red;
}
.app-container >>> .el-row .el-form-item--mini {
  margin-bottom: 0px;
}
</style>
